<template>
  <div class="container">
    <el-row>
      <!-- 手机型号活跃用户量排行 -->
      <el-card shadow="hover" class="section-card">
        <div slot="header">
          <span class="echart-title">手机型号活跃用户量排行</span>
          <div class="section-card-toolbar">
            <date-range-picker
              v-model="dateRange['deviceModel']"
              :clearable="false"
              type="daterange"
              align="right"
              unlink-panels
              range-separator="~"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              size="small"
              class="w-240"
              shortcuts="B"
              @change="(date)=>timeChange(date,'deviceModel')"/>
            <el-select v-model="listQuery['deviceModel'].country" size="small" class="w-120" >
              <el-option label="全部地区" value=""/>
              <el-option v-for="(key,item) in countryOpt" :key="key" :label="item" :value="key"/>
            </el-select>
            <el-select v-model="listQuery['deviceModel'].topCount" size="small" class="w-80" >
              <el-option v-for="item in countOpt" :key="item" :label="item" :value="item"/>
            </el-select>
            <el-button type="primary" icon="el-icon-search" size="small" @click="search('deviceModel')">搜索</el-button>
            <el-button size="small" @click="toExport('deviceModel')">导出</el-button>
          </div>
        </div>
        <div id="deviceModelAnalyze" class="echart-body menu" style="width:100%;height:500px;"/>
      </el-card>
      <!-- App系统分析 -->
      <el-card shadow="hover" class="section-card">
        <div slot="header">
          <span class="echart-title">App系统活跃用户量排行</span>
          <div class="section-card-toolbar">
            <date-range-picker
              v-model="dateRange['appVersion']"
              :clearable="false"
              type="daterange"
              align="right"
              unlink-panels
              range-separator="~"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              size="small"
              class="w-240"
              @change="(date)=>timeChange(date,'appVersion')"/>
            <el-select v-model="listQuery['appVersion'].country" size="small" class="w-120" >
              <el-option label="全部地区" value=""/>
              <el-option v-for="(key,item) in countryOpt" :key="key" :label="item" :value="key"/>
            </el-select>
            <el-select v-model="listQuery['appVersion'].platform" size="small" class="w-120" >
              <el-option label="全部渠道" value=""/>
              <el-option v-for="(key,item) in platformOpt" :key="key" :label="item" :value="key"/>
            </el-select>
            <el-select v-model="listQuery['appVersion'].topCount" size="small" class="w-80" >
              <el-option v-for="item in countOpt" :key="item" :label="item" :value="item"/>
            </el-select>
            <el-button type="primary" icon="el-icon-search" size="small" @click="search('appVersion')">搜索</el-button>
            <el-button size="small" @click="toExport('appVersion')">导出</el-button>
          </div>
        </div>
        <div id="appVersionAnalyze" class="echart-body menu" style="width:100%;height:400px;"/>
      </el-card>
      <!-- 运营商分析 -->
      <el-card shadow="hover" class="section-card">
        <div slot="header">
          <span class="echart-title">运营商分析</span>
          <div class="section-card-toolbar">
            <date-range-picker
              v-model="dateRange['deviceNetType']"
              :clearable="false"
              type="daterange"
              align="right"
              unlink-panels
              range-separator="~"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              size="small"
              class="w-240"
              @change="(date)=>timeChange(date,'deviceNetType')"/>
            <el-select v-model="listQuery['deviceNetType'].country" size="small" class="w-120" >
              <el-option label="全部地区" value=""/>
              <el-option v-for="(key,item) in countryOpt" :key="key" :label="item" :value="key"/>
            </el-select>
            <el-button type="primary" icon="el-icon-search" size="small" @click="search('deviceNetType')">搜索</el-button>
            <el-button size="small" @click="toExport('deviceNetType')">导出</el-button>
          </div>
        </div>
        <div class="echart-body" style="width:100%;height:450px;">
          <div id="deviceNetType" style="width:40%;height:420px;display:inline-block;"/>
          <div style="width:58%;height:400px;float: right;">
            <el-table :data="tableData['deviceNetType']" height="430" style="width: 100%" >
              <el-table-column prop="deviceNetType" label="运营商" align="center"/>
              <el-table-column prop="activeUserCount" label="活跃用户(人)" align="center"/>
              <el-table-column prop="activeUserPercent" label="活跃用户占比" align="center"/>
              <el-table-column prop="newUserCount" label="新增用户(人)" align="center"/>
              <el-table-column prop="newUserPercent" label="新增用户占比" align="center"/>
            </el-table>
          </div>
        </div>

      </el-card>
    </el-row>
  </div>
</template>
<script>
import echarts from 'echarts';
import { dateShortcutKeyJS } from '@/mixins/index.js';
import timeUtils from '@/utils/timeHandle.js';
const { exportJsonToExcel, formatJson } = require('@/utils/excel/Export2Excel');
import '@/assets/css/common/style.scss';

import {
  getDeviceModelAnalyzeApi,
  getAppVersionAnalyzeApi,
  getDeviceNetTypeApi
} from '@/api/user-analysis.js';

export default {
  mixins: [dateShortcutKeyJS],
  data() {
    return {
      dateRange: {
        deviceModel: [
          timeUtils.timeHandle(
            new Date().getTime() - 3600 * 1000 * 24 * 6,
            'date'
          ),
          timeUtils.timeHandle(new Date().getTime(), 'date')
        ],
        appVersion: [
          timeUtils.timeHandle(
            new Date().getTime() - 3600 * 1000 * 24 * 6,
            'date'
          ),
          timeUtils.timeHandle(new Date().getTime(), 'date')
        ],
        deviceNetType: [
          timeUtils.timeHandle(
            new Date().getTime() - 3600 * 1000 * 24 * 6,
            'date'
          ),
          timeUtils.timeHandle(new Date().getTime(), 'date')
        ]
      },
      listQuery: {
        deviceModel: {
          dateType: 1,
          country: '',
          startTime: timeUtils.timeHandle(
            new Date().getTime() - 3600 * 1000 * 24 * 6,
            'date'
          ),
          endTime: timeUtils.timeHandle(new Date().getTime(), 'date'),
          topCount: 20
        }, // 手机型号活跃用户量排行 参数
        appVersion: {
          dateType: 1,
          country: '',
          platform: '',
          startTime: timeUtils.timeHandle(
            new Date().getTime() - 3600 * 1000 * 24 * 6,
            'date'
          ),
          endTime: timeUtils.timeHandle(new Date().getTime(), 'date'),
          topCount: 10
        },
        deviceNetType: {
          dateType: 1,
          country: '',
          startTime: timeUtils.timeHandle(
            new Date().getTime() - 3600 * 1000 * 24 * 6,
            'date'
          ),
          endTime: timeUtils.timeHandle(new Date().getTime(), 'date')
        }
      },
      countryOpt: {
        中国: 'China',
        柬埔寨: 'Cambodia',
        其他: 'Other'
      },
      platformOpt: {
        安卓: 1,
        IOS: 2
      },
      countOpt: [10, 20, 30],
      deviceModelAnalyze: null,
      appVersionAnalyze: null,
      deviceNetType: null,
      tableData: {
        deviceModel: [],
        appVersion: [],
        deviceNetType: []
      }
    };
  },
  computed: {
    isOpenMenu() {
      return this.$store.state.app.sidebar.opened; // 监听菜单是否展开
    }
  },
  watch: {
    isOpenMenu(newVal, oldVal) {
      if (newVal) {
        document
          .getElementById('deviceModelAnalyze')
          .classList.add('menu-open');
        document.getElementById('appVersionAnalyze').classList.add('menu-open');
        setTimeout(() => {
          this.deviceModelAnalyze.resize();
          this.appVersionAnalyze.resize();
        }, 500);
      } else {
        document
          .getElementById('deviceModelAnalyze')
          .classList.remove('menu-open');
        document
          .getElementById('appVersionAnalyze')
          .classList.remove('menu-open');
      }
    }
  },
  mounted() {
    this.getDeviceModelList();
    this.getAppVersionList();
    this.getDeviceNetType();
    window.addEventListener('resize', () => {
      this.deviceModelAnalyze.resize();
      this.appVersionAnalyze.resize();
      this.deviceNetType.resize();
    });
  },
  methods: {
    getDeviceModelList() {
      this.deviceModelAnalyze = echarts.init(
        document.getElementById('deviceModelAnalyze')
      );
      this.deviceModelAnalyze.showLoading();
      getDeviceModelAnalyzeApi(this.listQuery['deviceModel'])
        .then(result => {
          if (result.code == 200) {
            this.tableData.deviceModel = result.data;
            const deviceModel = result.data
              .map(item => item.deviceModel)
              .reverse();
            const count = result.data.map(item => item.count).reverse();
            // 获取数据初始化
            this.deviceModelAnalyze.hideLoading();
            this.deviceModelAnalyze.setOption({
              color: this.$store.state.app.eChartColor,
              tooltip: {
                trigger: 'axis',
                axisPointer: {
                  type: 'shadow'
                }
              },
              grid: {
                left: '3%',
                right: '4%',
                bottom: '3%',
                containLabel: true
              },
              xAxis: {
                type: 'value',
                boundaryGap: [0, 0.01]
              },
              yAxis: {
                type: 'category',
                data: deviceModel
              },
              series: [
                {
                  name: '活跃用户数量(人)',
                  type: 'bar',
                  data: count
                }
              ]
            });
          } else {
            this.deviceModelAnalyze.hideLoading();
            this.$message.error(result.msg);
          }
        })
        .catch(() => {
          this.deviceModelAnalyze.hideLoading();
        });
    },
    getAppVersionList() {
      this.appVersionAnalyze = echarts.init(
        document.getElementById('appVersionAnalyze')
      );
      this.appVersionAnalyze.showLoading();
      getAppVersionAnalyzeApi(this.listQuery['appVersion'])
        .then(result => {
          if (result.code == 200) {
            this.tableData['appVersion'] = result.data;
            const appVersion = result.data.map(item => item.appVersion).reverse();
            const count = result.data.map(item => item.count).reverse();
            // 获取数据初始化
            this.appVersionAnalyze.hideLoading();
            this.appVersionAnalyze.setOption({
              color: this.$store.state.app.eChartColor,
              tooltip: {
                trigger: 'axis',
                axisPointer: {
                  type: 'shadow'
                }
              },
              grid: {
                left: '3%',
                right: '4%',
                bottom: '3%',
                containLabel: true
              },
              xAxis: {
                type: 'value',
                boundaryGap: [0, 0.01]
              },
              yAxis: {
                type: 'category',
                data: appVersion
              },
              series: [
                {
                  name: '活跃用户数量(人)',
                  type: 'bar',
                  data: count
                }
              ]
            });
          } else {
            this.deviceModelAnalyze.hideLoading();
            this.$message.error(result.msg);
          }
        })
        .catch(() => {
          this.deviceModelAnalyze.hideLoading();
        });
    },
    getDeviceNetType() {
      this.deviceNetType = echarts.init(
        document.getElementById('deviceNetType')
      );
      this.deviceNetType.showLoading();
      getDeviceNetTypeApi(this.listQuery['deviceNetType'])
        .then(result => {
          if (result.code == 200) {
            this.tableData['deviceNetType'] = result.data;
            const deviceNetType = result.data.map(item => item.deviceNetType);
            const count = result.data.map(item => {
              item.value = item.activeUserCount;
              item.name = item.deviceNetType;
              return item;
            });
            // 获取数据初始化
            this.deviceNetType.hideLoading();
            this.deviceNetType.setOption({
              title: {
                text: '活跃用户占比前10的运营商',
                left: 'center',
                top: 0
              },
              tooltip: {
                trigger: 'item',
                formatter: '{b} : {c} ({d}%)'
              },
              legend: {
                bottom: -5,
                left: 'center',
                data: deviceNetType
              },
              color: this.$store.state.app.eChartColor,
              series: [
                {
                  type: 'pie',
                  radius: '65%',
                  minAngle: 5, // 最小的扇区角度（0 ~ 360），用于防止某个值过小导致扇区太小影响交互
                  avoidLabelOverlap: true, // 是否启用防止标签重叠策略
                  center: ['50%', '50%'],
                  data: count,
                  itemStyle: {
                    emphasis: {
                      shadowBlur: 10,
                      shadowOffsetX: 0,
                      shadowColor: 'rgba(0, 0, 0, 0.5)'
                    }
                  }
                }
              ]
            });
          } else {
            this.deviceNetType.hideLoading();
            this.$message.error(result.msg);
          }
        })
        .catch(() => {
          this.deviceNetType.hideLoading();
        });
    },
    timeChange(time, type) {
      if (!time) return;
      const startTime = Date.parse(time[0]);
      const endTime = Date.parse(time[1]);
      this.listQuery[type].startTime = timeUtils.timeHandle(time[0], 'date');
      this.listQuery[type].endTime = timeUtils.timeHandle(time[1], 'date');
      const Days = Math.floor(Math.abs(endTime - startTime) / (24 * 3600 * 1000));
      if (Days <= 30) {
        this.listQuery[type].dateType = 1;
      } else if (Days > 30 && Days <= 48) {
        this.listQuery[type].dateType = 2;
      } else if (Days > 48) {
        this.listQuery[type].dateType = 3;
      }
    },
    search(type) {
      switch (type) {
        case 'deviceModel':
          this.getDeviceModelList();
          break;
        case 'appVersion':
          this.getAppVersionList();
          break;
        case 'deviceNetType':
          this.getDeviceNetType();
          break;
      }
    },
    toExport(type) {
      let tHeader, tKey, tableData, title;
      // eslint-disable-next-line prefer-const
      tableData = this.tableData[type].map(item => {
        item.date = `${this.listQuery[type].startTime} ~ ${
          this.listQuery[type].endTime
        } `;
        return item;
      });
      switch (type) {
        case 'deviceModel':
          tHeader = ['终端', '日期', '活跃用户(人)'];
          // 表头对应字段名，要和下面数据key对应
          tKey = ['deviceModel', 'date', 'count'];
          title = '手机型号活跃用户量排行';
          break;
        case 'appVersion':
          tHeader = ['系统版本', '日期', '活跃用户(人)'];
          tKey = ['appVersion', 'date', 'count'];
          title = 'App系统分析';
          break;
        case 'deviceNetType':
          tHeader = [
            '日期',
            '运营商',
            '活跃用户(人)',
            '活跃占比',
            '新增用户(人)',
            '新增占比'
          ];
          tKey = [
            'date',
            'deviceNetType',
            'activeUserCount',
            'activeUserPercent',
            'newUserCount',
            'newUserPercent'
          ];
          title = '运营商分析';
          break;
      }
      // 数据来源
      const data = formatJson(tKey, tableData); // 数据格式化
      const newDay = timeUtils.timeHandle(new Date().getTime(), 'date');
      const fileName = `${title}${newDay}`; // 导出时文件名
      exportJsonToExcel(tHeader, data, fileName); // 导出文件
    }
  }
};
</script>
